package com.rljk.service.impl;

import com.alibaba.fastjson.JSONObject;
import com.rljk.common.consts.EnergyEnum;
import com.rljk.common.consts.ThirdLoginEnum;
import com.rljk.common.consts.WealthTypeEnum;
import com.rljk.config.ThirdLoginConfig;
import com.rljk.domain.common.PageData;
import com.rljk.service.AssetsManager;
import com.rljk.service.ThirdLoginManager;
import com.rljk.service.UserManager;
import com.rljk.service.WealthManager;
import com.rljk.utils.HttpClientUtils;
import com.rljk.utils.SnowIdUtil;
import com.rljk.utils.Tools;
import com.rljk.utils.URLEncodeUtil;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import weibo4j.Users;
import weibo4j.model.User;

import javax.annotation.Resource;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;
import java.util.SortedMap;
import java.util.TreeMap;


/**
 * Author:   YASUO
 * Date:     2018/8/8 16:33
 * Description:
 */
@Service("thirdLoginService")
@Slf4j
public class ThirdLoginService implements ThirdLoginManager{

    @Autowired
    private ThirdLoginConfig constants;

    @Resource(name = "openuserService")
    private OpenuserService openuserService;

    @Resource(name = "wealthService")
    private WealthManager wealthService;

    @Resource(name = "assetsService")
    private AssetsManager assetsService;



    @Override
    public String getWeiBoCode() throws Exception {
        String url = "https://api.weibo.com/oauth2/authorize?client_id=YOUR_CLIENT_ID&response_type=code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI";
        url =  url.replace("YOUR_CLIENT_ID", constants.getWeiBoAppId()).replace("YOUR_CLIENT_SECRET", URLEncodeUtil.getURLEncoderString(constants.getWeiBoAppSecret())).
                replace("YOUR_REGISTERED_REDIRECT_URI",constants.getWeiBoRedirectUrl());
        String result = HttpClientUtils.get(url.toString(),"UTF-8");
        log.debug("result:"+result);
        return result;
    }

    /**
     *  weibo根据code获取accessToken(仅支持post)
     *  {
     "access_token": "2.00Fn44OHtaDFYD0df1278a1czzSaEC",
     "remind_in": "157679999",
     "expires_in": 157679999,
     "uid": "6625371527",
     "isRealName": "true"
     }
     */
    @Override
    public String getWeiBoAccessToken(String code)throws  Exception{
//        String url = "https://api.weibo.com/oauth2/access_token?client_id=YOUR_CLIENT_ID&client_secret=YOUR_CLIENT_SECRET&grant_type=authorization_code&redirect_uri=YOUR_REGISTERED_REDIRECT_URI&code=CODE";
//        url =  url.replace("YOUR_CLIENT_ID", constants.getWeiBoAppId()).replace("YOUR_CLIENT_SECRET", constants.getWeiBoAppSecret()).
//                replace("YOUR_REGISTERED_REDIRECT_URI",URLEncodeUtil.getURLEncoderString(constants.getWeiBoRedirectUrl())).replace("CODE",code);


        log.info(" weibo根据code获取accessToken(仅支持post)");
        log.info("请求参数"+code);
        String url = "https://api.weibo.com/oauth2/access_token";
        SortedMap<String, Object> map = new TreeMap<>();
        map.put("client_id", constants.getWeiBoAppId());
        map.put("client_secret", constants.getWeiBoAppSecret());
        map.put("grant_type", "authorization_code");
        map.put("redirect_uri", constants.getWeiBoRedirectUrl());
        map.put("code", code);
        String result = com.rljk.utils.HttpClientUtil.httpPostRequest(url,map);

        log.info("weibo根据code获取accessToken(仅支持post)结果result:"+result);
        return result;
    }



    /**
     *  weibo根据access_token和uid(openid)获取用户基本信息
     *  {
     "id": 6625371527,	用户UID
     "idstr": "6625371527",字符串型的用户UID
     "class": 1,
     "screen_name": "wolve900",用户昵称
     "name": "wolve900",	友好显示名称
     "province": "11",
     "city": "1000",
     "location": "北京",	用户所在地
     "description": "",
     "url": "",
     "profile_image_url": "http://tvax4.sinaimg.cn/default/images/default_avatar_male_50.gif",	用户头像地址（中图），50×50像素
     "cover_image_phone": "http://ww1.sinaimg.cn/crop.0.0.640.640.640/549d0121tw1egm1kjly3jj20hs0hsq4f.jpg",	用户的微博统一URL地址
     "profile_url": "u/6625371527",
     "domain": "",
     "weihao": "",
     "gender": "m",性别，m：男、f：女、n：未知
     "followers_count": 1,
     "friends_count": 62,
     "pagefriends_count": 0,
     "statuses_count": 0,
     "video_status_count": 0,
     "favourites_count": 0,
     "created_at": "Tue Aug 07 19:16:43 +0800 2018",
     "following": false,
     "allow_all_act_msg": false,
     "geo_enabled": true,
     "verified": false,
     "verified_type": -1,
     "remark": "",
     "insecurity": {
     "sexual_content": false
     },
     "ptype": 0,
     "allow_all_comment": true,
     "avatar_large": "http://tvax4.sinaimg.cn/default/images/default_avatar_male_180.gif",用户头像地址（大图），180×180像素
     "avatar_hd": "http://tvax4.sinaimg.cn/default/images/default_avatar_male_180.gif",	用户头像地址（高清），高清头像原图
     "verified_reason": "",
     "verified_trade": "",
     "verified_reason_url": "",
     "verified_source": "",
     "verified_source_url": "",
     "follow_me": false,
     "like": false,
     "like_me": false,
     "online_status": 0,
     "bi_followers_count": 0,
     "lang": "zh-cn",
     "star": 0,
     "mbtype": 0,
     "mbrank": 0,
     "block_word": 0,
     "block_app": 0,
     "credit_score": 80,
     "user_ability": 0,
     "urank": 0,
     "story_read_state": -1,
     "vclub_member": 0
     }
     */
    @Override
    @Transactional
    public PageData getWeiBoUserInfo(String resutlGetWeiBoAccessToken)throws  Exception{

        log.info("weibo根据access_token和uid获取用户基本信息");
        log.info("请求参数:"+resutlGetWeiBoAccessToken);
        JSONObject accesstokenResult = JSONObject.parseObject(resutlGetWeiBoAccessToken);
        if(Tools.notEmpty(accesstokenResult.getString("error_code"))){
            PageData pd = new PageData();
            pd.put("error","invalid authorization code");
            return pd;
        }
        String uid = accesstokenResult.getString("uid");
        log.info("微博uid:"+uid);
        String access_token = accesstokenResult.getString("access_token");
        log.info("微博access_token:"+access_token);

        PageData pd = new PageData();
        pd.put("OPENID",uid);
        PageData openUser = openuserService.findById(pd);
        if(openUser!=null){
            log.info("直接返回");
            return openUser;
        }
        log.info("发送请求查询用户");

        //String url = "https://api.weibo.com/2/eps/user/info.json";
        //String url = "https://c.api.weibo.com/2/users/show/biz.json";//api   http://open.weibo.com/wiki/C/2/users/show/biz
//        String url = "https://api.weibo.com/2/users/show.json?access_token=ACCESS_TOKEN&uid=UID&source=SOURCE";
//        url.replace("ACCESS_TOKEN",access_token).replace("UID",uid).replace("SOURCE",constants.getWeiBoAppId());
        String url = "https://api.weibo.com/2/users/show.json";

        SortedMap<String, Object> map = new TreeMap<>();
        map.put("access_token", access_token);
        map.put("uid", uid);
        map.put("source", constants.getWeiBoAppId());
        String result = com.rljk.utils.HttpClientUtil.httpGetRequest(url,map);
//
//        log.info("请求参数postJson："+postJson.toJSONString());

        //String result = HttpClientUtil.post(url, postJson.toJSONString());
        //log.info("weibo获取用户基本信息请求url："+url);
        log.info(" weibo获取用户基本信息结果result:"+result);

        JSONObject json = JSONObject.parseObject(result);
        if(Tools.notEmpty(json.getString("error"))){
            pd.put("error","applications over the unaudited use restrictions  21321");
            return pd;

        }
        pd.put("OPENUSER_ID", SnowIdUtil.getSnowId());
        pd.put("OPENTYPE", ThirdLoginEnum.WEIBO.getCode());
        pd.put("ACCESSTOKE", access_token);
        pd.put("EXPIREDTIME", accesstokenResult.get("expires_in"));
        pd.put("NICKNAME", json.get("name"));
        if(json.get("gender").equals("m")){
            pd.put("SEX", "1");
        } else if(json.get("gender").equals("f")){
            pd.put("SEX", "2");
        } else {
            pd.put("SEX", "0");
        }
        pd.put("PORTRAIT", json.get("profile_image_url"));
        openuserService.save(pd);
        //初始化资产
        initAsserts(uid);
        return pd;
    }


    /**
     *  weibo根据access_token和uid(openid)获取用户基本信息
     */
//    @Override
//    public Object getWeiBoUserInfoBySDK(String resutlGetWeiBoAccessToken)throws  Exception{
//
//        log.info("weibo根据access_token和uid获取用户基本信息");
//        JSONObject accesstokenResult = JSONObject.parseObject(resutlGetWeiBoAccessToken);
//        if(Tools.notEmpty(accesstokenResult.getString("error_code"))){
//            PageData pd = new PageData();
//            pd.put("error","invalid authorization code");
//            return pd;
//        }
//        String uid = accesstokenResult.getString("uid");
//        log.info("微博uid:"+uid);
//        String access_token = accesstokenResult.getString("access_token");
//        log.info("微博access_token:"+access_token);
//        Users um = new Users(access_token);
//        try {
//            User user = um.showUserById(uid);
//            log.info("微博用户："+user.toString());
//            return user;
//        } catch (Exception e) {
//            e.printStackTrace();
//        }
//        return null;
//    }

    /**
     * qq获取code
     * https://graph.qq.com/oauth2.0/authorize?response_type=code&client_id=101497856&redirect_uri=http://gem.rongyaohk.com/thirdlogin/getqquserinfo&state=ok
     */
    @Override
    public String getQQoCode() throws Exception {
        log.info("qq获取code");
        //拼接url
        StringBuilder url = new StringBuilder();
        url.append("https://graph.qq.com/oauth2.0/authorize?");
        url.append("response_type=code");
        url.append("&client_id=" + constants.getQqAppId());
        //回调地址 ,回调地址要进行Encode转码
        String redirect_uri = constants.getQqRedirectUrl();
        //转码
        url.append("&redirect_uri="+ URLEncodeUtil.getURLEncoderString(redirect_uri));
        url.append("&state=ok");
        log.info("url.toString():"+url.toString());
        String result = HttpClientUtils.get(url.toString(),"UTF-8");
        log.info("result(code):"+result);
        return  result;
    }

    /**
     * qq获取token,该步骤返回的token期限为一个月
     * https://graph.qq.com/oauth2.0/token?grant_type=authorization_code&client_id=&client_secret=&code=
     */
    @Override
    public String getQQAccessToken(String code) throws Exception {
        log.info("qq获取token");
        log.info("请求参数code:"+code);
        StringBuilder url = new StringBuilder();
        url.append("https://graph.qq.com/oauth2.0/token?");
        url.append("grant_type=authorization_code");
        url.append("&client_id=" + constants.getQqAppId());
        url.append("&client_secret=" + constants.getQqAppSecret());
        url.append("&code=" + code);  //注意此code会在10分钟内过期。
        //回调地址
        String redirect_uri = constants.getQqRedirectUrl();
        //转码
        url.append("&redirect_uri="+ URLEncodeUtil.getURLEncoderString(redirect_uri));
        log.info("url.toString():"+url.toString());
        String result = HttpClientUtils.get(url.toString(),"UTF-8");
        log.info("result:"+result);
        //把token保存
//        String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(result, "&");

//        String accessToken = StringUtils.substringAfterLast(items[0], "=");
//        Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));
//        String refreshToken = StringUtils.substringAfterLast(items[2], "=");
        return result;
    }

    /**
     * qq获取用户openId
     * @return
     * @throws Exception
     */
    @Override
    public String getQQOpenId(String accessToken) throws Exception {
        log.info("qq获取用户openId");
        StringBuilder url = new StringBuilder("https://graph.qq.com/oauth2.0/me?");
        //获取保存的用户的token
        if (!StringUtils.isNotEmpty(accessToken)){
            return "未授权";
        }
        url.append("access_token=" + accessToken);
        log.debug("url.toString():"+url.toString());
        String result = HttpClientUtils.get(url.toString(),"UTF-8");
        log.debug("result:"+result);
        String openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
        log.debug("openId:"+openId);
        return result;
    }

    /**
     * q刷新token(可选)  refreshToken
     * @param refreshToken
     * @return
     * @throws Exception
     */
    @Override
    public String refreshQQToken(String refreshToken) throws Exception {
        log.info("qq刷新token");
        StringBuilder url = new StringBuilder("https://graph.qq.com/oauth2.0/token?");
        url.append("grant_type=refresh_token");
        url.append("&client_id=" + constants.getQqAppId());
        url.append("&client_secret=" + constants.getQqAppSecret());
        //获取refreshToken
//        String refreshToken = pd.getString("refreshToken");
        url.append("&refresh_token=" + refreshToken);  // 该处需要传入上个步骤获取到的refreshToken;
        log.debug("url.toString():"+url.toString());
        String result = HttpClientUtils.get(url.toString(),"UTF-8");
        log.debug("result:"+result);
        return result;
    }

    /**
     * https://graph.qq.com/user/get_user_info?access_token=844297D977590AD2582E9B7C13B6A1FE&oauth_consumer_key=101497856&openid=8CA79CE4785268D84B703C20E8A6A3EF
     * @param qqcode
     * @return
     * @throws Exception
     * {
    "ret": 0,
    "msg": "",
    "is_lost": 0,
    "nickname": "往后余生",
    "gender": "男",
    "province": "",
    "city": "",
    "year": "0",
    "constellation": "",
    "figureurl": "http://qzapp.qlogo.cn/qzapp/101497856/8CA79CE4785268D84B703C20E8A6A3EF/30",
    "figureurl_1": "http://qzapp.qlogo.cn/qzapp/101497856/8CA79CE4785268D84B703C20E8A6A3EF/50",
    "figureurl_2": "http://qzapp.qlogo.cn/qzapp/101497856/8CA79CE4785268D84B703C20E8A6A3EF/100",
    "figureurl_qq_1": "http://thirdqq.qlogo.cn/qqapp/101497856/8CA79CE4785268D84B703C20E8A6A3EF/40",
    "figureurl_qq_2": "http://thirdqq.qlogo.cn/qqapp/101497856/8CA79CE4785268D84B703C20E8A6A3EF/100",
    "is_yellow_vip": "0",
    "vip": "0",
    "yellow_vip_level": "0",
    "level": "0",
    "is_yellow_year_vip": "0"
    }
     */
    @Override
    @Transactional
    public Object getQQUserInfo(String qqcode) throws Exception {
        log.info("请求参数qqcode:"+qqcode);
        String resultQqAccessToken = getQQAccessToken(qqcode);
        //把token保存
        String[] items = StringUtils.splitByWholeSeparatorPreserveAllTokens(resultQqAccessToken, "&");
        String accessToken = StringUtils.substringAfterLast(items[0], "=");
        Long expiresIn = new Long(StringUtils.substringAfterLast(items[1], "="));
//        String refreshToken = StringUtils.substringAfterLast(items[2], "=");
        StringBuilder url = new StringBuilder("https://graph.qq.com/oauth2.0/me?");
        if (!StringUtils.isNotEmpty(accessToken)){
            return "未授权";
        }
        url.append("access_token=" + accessToken);
        log.info("url.toString():"+url.toString());
        String result = HttpClientUtils.get(url.toString(),"UTF-8");
        log.info("result:"+result);
        //String openId = StringUtils.substringBetween(result, "\"openid\":\"", "\"}");
        result = result.replace("callback","").replace("(","").replace(")","").replace(";","").trim();
        log.info("处理后的result:"+result);
        JSONObject json = JSONObject.parseObject(result);
        log.info("json:"+json);
        String openid = json.getString("openid");
        String client_id = json.getString("client_id");
        log.info("openId:"+openid);
        log.info("client_id:"+client_id);

        PageData pd = new PageData();
        pd.put("OPENID",openid);
        //判断第三方登录是否已经注册
        PageData openUser = openuserService.findById(pd);
        if(openUser!=null){
            log.info("直接返回");
            return openUser;
        }
        log.info("发送请求查询用户");
        //String url1 = "https://graph.qq.com/user/get_user_info?access_token=YOUR_ACCESS_TOKEN&oauth_consumer_key=YOUR_APP_ID&openid=YOUR_OPENID";
        //url1.replace("YOUR_ACCESS_TOKEN",accessToken).replace("YOUR_APP_ID",constants.getQqAppId()).replace("YOUR_OPENID",openid);
        StringBuilder url1 = new StringBuilder("https://graph.qq.com/user/get_user_info?");
        url1.append("access_token=" + accessToken).append("&oauth_consumer_key="+constants.getQqAppId()).append("&openid="+openid);
        String result1 = HttpClientUtils.get(url1.toString(),"UTF-8");
        log.info("qq用户信息:"+result1);

        JSONObject json1 = JSONObject.parseObject(result1);


        //第三方插入数据
        pd.put("OPENUSER_ID", SnowIdUtil.getSnowId());
        pd.put("OPENTYPE", ThirdLoginEnum.QQ.getCode());
        pd.put("ACCESSTOKE", accessToken);
        pd.put("EXPIREDTIME", expiresIn);
        pd.put("NICKNAME", json1.get("nickname"));
        if(json1.get("gender").equals("男")) {
            pd.put("SEX", "1");
        } else if(json1.get("gender").equals("女")){
            pd.put("SEX", "2");
        } else {
            pd.put("SEX", "0");
        }
        pd.put("PORTRAIT", json1.get("figureurl_qq_2"));
        openuserService.save(pd);

        //初始化资产
        initAsserts(openid);
        return pd;
    }

    /**
     * @Author zhang
     * @Description 登录签到功能
     * @Date 2018/8/10 19:17
     * @Param [userId]
     * @return java.lang.String
     **/
    @Override
    public String signIn(String userId) throws Exception {

        PageData pd = new PageData();

        Date date = new Date();
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd");
        String nowTime = sdf.format(date);

        pd.put("USER_ID",userId);
        pd.put("CREATE_TIME",nowTime + "%");

        List<PageData> wealthInfo = wealthService.getWealthValue(pd);

        if (wealthInfo.size() != 0){
            return "已签到！";
        }else {

            pd.remove("CREATE_TIME");

            PageData assetsInfo = assetsService.findById(pd);

            pd.put("WEALTH_ID",SnowIdUtil.getSnowId());
            pd.put("WEALTH_VALUE", EnergyEnum.valueOf("DAY_SIGN").getSocre());
            //System.out.println(pd.get("WEALTH_VALUE"));
            pd.put("WEALTH_TYPE", WealthTypeEnum.ENERGY.getCode());
            pd.put("GET_TYPE", EnergyEnum.DAY_SIGN.getCode());

            wealthService.save(pd);

            pd.remove("WEALTH_ID");
            pd.remove("WEALTH_VALUE");
            pd.remove("WEALTH_TYPE");
            pd.remove("GET_TYPE");

            Double energyValue = (Double)assetsInfo.get("ENERGY_VALUE");
            pd.put("ENERGY_VALUE",energyValue + EnergyEnum.valueOf("DAY_SIGN").getSocre());
            //System.out.println("ENERGY_VALUE==========" + EnergyEnum.valueOf("DAY_SIGN").getSocre());
            //System.out.println("ENERGY_VALUE=========="+energyValue);
            assetsService.edit(pd);

            return "签到成功！";

        }

    }

    /**
     *  微信登录获取授权码
     *  https://open.weixin.qq.com/connect/qrconnect?appid=wx4cd7b2b3aba3aea5&redirect_uri=http%3A%2F%2Fh5.zgjszl.com%2F%23%2F&response_type=code&scope=snsapi_login
     */
    @Override
    public String getWechatCode() throws Exception {
        log.info("微信登录获取授权码");
        //拼接url
        StringBuilder url = new StringBuilder();
        url.append("https://open.weixin.qq.com/connect/qrconnect?");
        url.append("response_type=code");
        url.append("&appid=" + constants.getWeChatAppId());
        //回调地址 ,回调地址要进行Encode转码
        String redirect_uri = constants.getWeChatRedirectUrl();
        //转码
        url.append("&redirect_uri="+ URLEncodeUtil.getURLEncoderString(redirect_uri));
        url.append("&scope=snsapi_login");
        log.info("url.toString():"+url.toString());
        String result = HttpClientUtils.get(url.toString(),"UTF-8");
        log.info("result(code):"+result);
        return  result;
    }

    /**
     * 微信登录根据获取accessToken
     * https://api.weixin.qq.com/sns/oauth2/access_token?appid=APPID&secret=SECRET&code=CODE&grant_type=authorization_code
     * @param wechatcode
     * return
     * {
    "access_token":"ACCESS_TOKEN",
    "expires_in":7200,
    "refresh_token":"REFRESH_TOKEN",
    "openid":"OPENID",
    "scope":"SCOPE",
    "unionid": "o6_bmasdasdsad6_2sgVt7hMZOPfL"
    }
     */
    @Override
    public String getWechatAccessToken(String wechatcode) throws Exception {
        log.info("微信登录根据获取accessToken");
        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/oauth2/access_token?");
        url.append("grant_type=authorization_code");
        url.append("&appid=" + constants.getWeChatAppId());
        url.append("&secret=" + constants.getWeChatAppSecret());
        url.append("&code=" + wechatcode);
        log.info("获取code的请求连接url.toString():"+url.toString());
        String result = HttpClientUtils.get(url.toString(),"UTF-8");
        log.info("获取code的请求结果result:"+result);
        return result;
    }

    /**
     *  微信登录获取用户信息
     *  https://api.weixin.qq.com/sns/userinfo?access_token=ACCESS_TOKEN&openid=OPENID
     * @param wechatcode
     * @return
     * @throws Exception
     * {
    "openid":"OPENID",
    "nickname":"NICKNAME",
    "sex":1,
    "province":"PROVINCE",
    "city":"CITY",
    "country":"COUNTRY",
    "headimgurl": "http://wx.qlogo.cn/mmopen/g3MonUZtNHkdmzicIlibx6iaFqAc56vxLSUfpb6n5WKSYVY0ChQKkiaJSgQ1dZuTOgvLLrhJbERQQ4eMsv84eavHiaiceqxibJxCfHe/0",
    "privilege":[
    "PRIVILEGE1",
    "PRIVILEGE2"
    ],
    "unionid": " o6_bmasdasdsad6_2sgVt7hMZOPfL"

    }
     */
    @Override
    @Transactional
    public Object getWechatUserInfo(String wechatcode) throws Exception {
        log.info("微信登录获取用户信息");
        log.info("请求参数code:"+wechatcode);
        String resultWechatAccessToken = getWechatAccessToken(wechatcode);
        JSONObject wechatResult = JSONObject.parseObject(resultWechatAccessToken);
        String access_token = wechatResult.getString("access_token");
        log.info("用户的access_token:"+access_token);
        String openid = wechatResult.getString("openid");
        log.info("用户的openid:"+openid);

        PageData pd = new PageData();
        pd.put("OPENID",openid);
        //判断第三方登录是否已经注册
        PageData openUser = openuserService.findById(pd);
        if(openUser!=null){
            log.info("直接返回");
            return openUser;
        }
        log.info("发送请求查询用户");

        StringBuilder url = new StringBuilder("https://api.weixin.qq.com/sns/userinfo?");
        url.append("access_token=" + access_token);
        url.append("&openid=" + openid);
        log.info("微信登录获取用户信息url.toString():"+url.toString());
        String result = HttpClientUtils.get(url.toString(),"UTF-8");
        log.info("微信登录获取用户信息返回的result:"+result);
        //result = result.replace("callback","").replace("(","").replace(")","").replace(";","").trim();
        //log.info("处理后的result:"+result);
        JSONObject json = JSONObject.parseObject(result);
        log.info("微信登录获取用户信息返回的json:"+json);

        //第三方插入数据
        pd.put("OPENUSER_ID", SnowIdUtil.getSnowId());
        pd.put("OPENTYPE", ThirdLoginEnum.WECHAT.getCode());
        pd.put("ACCESSTOKE", access_token);
        pd.put("EXPIREDTIME", wechatResult.get("expires_in"));
        pd.put("NICKNAME", json.get("nickname"));
        pd.put("SEX", String.valueOf(json.get("sex")));
        pd.put("PORTRAIT", json.get("headimgurl"));
        openuserService.save(pd);

        //初始化资产
        initAsserts(openid);
        return pd;
    }

    public void initAsserts(String userId) throws Exception{
        PageData pd = new PageData();
        pd.put("USER_ID",userId);
        PageData asserts = assetsService.findById(pd);
        if(asserts==null){
            //初始化资产
            pd.put("ASSETS_ID",SnowIdUtil.getSnowId());
            assetsService.save(pd);
        }
    }


}
